package com.example.springboot_shiro.config;

import com.example.springboot_shiro.interceptor.JwtInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author: lqy
 * @date: 2021/8/31 10:47
 * @description:
 */
@Configuration
public class CorsConfig {

    @Bean
    public WebMvcConfigurer configurer() {
        return new WebMvcConfigurer() {
            //静态资源映射
            @Override
            public void addResourceHandlers(ResourceHandlerRegistry registry) {
                registry.addResourceHandler("/upload/**").addResourceLocations("file:D:/static/upload/");
                registry.addResourceHandler("/course/**").addResourceLocations("file:D:/static/course/");
            }

            //跨域
//            @Override
//            public void addCorsMappings(CorsRegistry registry) {
//                registry.addMapping("/**")
//                        .allowedOrigins("*")
//                        .allowedMethods("*")
//                        .allowedHeaders("*");
//            }
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(jwtInterceptor())
                        // 拦截所有请求，通过判断是否有 @LoginToken 注解 决定是否需要登录
                        .addPathPatterns("/**");
            }

            /**
             * jwt拦截器
             * @return
             */
            @Bean
            public JwtInterceptor jwtInterceptor() {
                return new JwtInterceptor();
            }

            @Bean
            public CorsFilter corsFilter() {
                CorsConfiguration config = new CorsConfiguration();
                // 注意这里，域不能写*，要写具体的值。不然cookie用不了
                config.addAllowedOrigin("http://192.168.3.64");
                config.setAllowCredentials(true);
                config.addAllowedMethod("OPTIONS");
                config.addAllowedMethod("HEAD");
                config.addAllowedMethod("GET");
                config.addAllowedMethod("PUT");
                config.addAllowedMethod("POST");
                config.addAllowedMethod("DELETE");
                config.addAllowedHeader("*");
                config.setMaxAge(360000L);
                UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
                configSource.registerCorsConfiguration("/**", config);
                return new CorsFilter(configSource);
            }

        };
    }

}
